<template>
    <div class="app-container">
        <div class="tjjs">
            <div v-if="this.$route.params && this.$route.params.id">编辑讲师</div>
            <div v-else>添加讲师</div>
        </div>
        <el-form ref="teacherForm" :model="teacher" label-width="80px" :rules="rules">
            <el-form-item label="讲师名称" prop="name">
                <el-input v-model="teacher.name"></el-input>
            </el-form-item>
            <el-form-item label="讲师排序" prop="sort">
                <el-input-number v-model="teacher.sort" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
            <el-form-item label="讲师头衔" prop="level">
                <el-select v-model="teacher.level" placeholder="请选择">
                    <el-option label="高级讲师" :value="1"></el-option>
                    <el-option label="首席讲师" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="讲师资历" prop="career">
                <el-input v-model="teacher.career"></el-input>
            </el-form-item>
            <el-form-item label="讲师简介" prop="intro">
                <el-input type="textarea" v-model="teacher.intro" rows="10"></el-input>
            </el-form-item>
            <el-form-item label="讲师头像">
                <panThumb :image="teacher.avatar"></panThumb>
                <el-button type="primary" class="el-icon-upload" @click="imageCropperShow = true">上传头像</el-button>
                <!-- 
                    key:头像剪裁插件的唯一标识
                    url：上传图片的api地址
                    field：请求api时需要发送的字段名（后端api所预定的）
                    close:关闭头像时调用的方法
                    crop-upload-success：头像上传成功时回调的方法
                 -->
                <imageCropper v-show="imageCropperShow" @close="close" :width="300" :height="300" :key="imageCropperKey" :url="`${BASE_URL}/file/upload?host=avatar`" field="file" @crop-upload-success="cropSuccess"></imageCropper>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import teacherApi from '@/api/teacher'
import panThumb from '../../components/PanThumb'
import imageCropper from '../../components/ImageCropper'
export default {
    components: { panThumb, imageCropper },
    data() {
        return {
            BASE_URL:process.env.BASE_API,
            imageCropperKey:1,//头像剪裁插件的key
            imageCropperShow: false,//头像剪裁插件是否显示
            teacher: {
                // name: '',  //讲师姓名
                // intro: '', // 简介
                // career: '', // 资历
                // level: 1, // 头衔
                avatar: "http://houpuyun-img.oss-cn-beijing.aliyuncs.com/avatar/2022/10/27/346909901135941.jpg"  // 头像
                // sort: 0  // 排序
            },
            // 格式验证
            rules: {
                name: [
                    { required: true, message: '请输入讲师名称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ],
                intro: [
                    { required: true, message: '请输入简介', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: "number", message: '必须为数字', trigger: 'blur' }
                ],
                career: [
                    { required: true, message: '请输入资历', trigger: 'blur' }
                ],
                level: [
                    { required: true, message: '请选择头衔', trigger: 'change' }
                ]
            }
        }
    },
    watch: {
        $route(to, from) {
            this.init()
        }
    },
    created() {
        this.init()
    },
    methods: {
        // 头像上传成功之后的回调方法
        cropSuccess(data){
            console.log(data);
            // 关闭头像剪裁插件
            this.imageCropperShow=false
            // 显示上传后的头像图片
            this.teacher.avatar=data.ossUrl
            // 修改头像插件的key，使其进行初始化
            this.imageCropperKey=this.imageCropperKey+1
        },
        // 关闭头像插件的显示
        close() {
            this.imageCropperShow = false
            // 修改头像插件的key，使其进行初始化
            this.imageCropperKey=this.imageCropperKey+1
        },
        onSubmit() {
            // 调用api前进行格式校验
            this.$refs["teacherForm"].validate((valid) => {
                if (valid) {
                    // 验证通过
                    if (this.teacher.id) {
                        console.log('编辑讲师');
                        this.updateTeacher();
                    } else {
                        this.addTeacher()
                    }
                } else {
                    // 格式校验失败
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addTeacher() {
            teacherApi.addTeacher(this.teacher).then(res => {
                // 提示成功信息
                this.$message({
                    type: 'success',
                    message: '添加成功!'
                })
                // 跳转讲师列表页面   通过编程式路由导航的方法
                this.$router.push({ path: '/teacher' })
            })
        },
        updateTeacher() {
            teacherApi.updateTeacher(this.teacher).then((res) => {
                this.$message({
                    type: "success",
                    message: "修改成功!",
                });
                //跳转至讲师列表页面，通过编程式路由
                this.$router.push({ path: "/teacher" });
            });
        },
        getTeacher(id) {
            teacherApi.teacherEdit(id).then((res) => {
                //将当前讲师的信息绑定到表单中
                this.teacher = res.data;
            }).catch((err) => {
                this.$message({
                    type: "error",
                    message: "获取失败!",
                });
            });
        },
        // 初始化页面
        init() {
            //根据路由判断当前是添加还是修改
            if (this.$route.params && this.$route.params.id) {
                // console.log(this.$router.params.id);
                //执行更新操作

                // 根据id调用获取讲师信息的api
                this.getTeacher(this.$route.params.id)
            } else {
                // console.log('执行添加');
                this.teacher = {
                    avatar: "http://houpuyun-img.oss-cn-beijing.aliyuncs.com/avatar/2022/10/27/346909901135941.jpg"
                };
            }
        },
        onCancel() {
            this.$message({
                message: "cancel!",
                type: "warning",
            });
        },
    },
}
</script>
<style scoped>
.tjjs {
    font-size: 25px;
    font-weight: bold;
    line-height: 40px;
}
</style>